//
//  TextSplitter.m
//  eBookr
//
//  Created by Zachary Brewster-Geisz on 9/26/07.
//  Copyright 2007 Zachary Brewster-Geisz. All rights reserved.
//

#import "TextSplitter.h"


@implementation TextSplitter
- (TextSplitter *)initWithOptionsDictionary:(NSDictionary *)opts
{
	self = [super init];
	optionsDictionary = [opts retain];
	splitType = [[optionsDictionary objectForKey:SPLIT_TYPE_KEY] intValue];
	if ((splitType == splitOnOther) || (splitType == splitOnOtherAndText))
		splitString = [optionsDictionary objectForKey:USER_SPLIT_STRING];
	
	NSLog(@"\nSplit type: %d\nSplit string:%@", splitType, splitString);
	
	return self;
}

- (BOOL)splitFile:(NSString *)filePath toDirectory:(NSString *)dirPath
{
	NSStringEncoding enc;
	originalText = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
	if (nil == originalText)
	{
		NSLog(@"originaltext is nil");
		return NO;
	}
	lowercaseText = [[originalText lowercaseString] retain];
	
	NSRange aRange = [lowercaseText rangeOfString:@"<html" options:NSLiteralSearch range:NSMakeRange(0, 1024)];
	if (NSNotFound == aRange.location)
	{
		// This must be plain text!
		return [self splitPlainText:filePath toDirectory:dirPath];
	}
	else
	{
		//This must be HTML!
		return [self splitHTML:filePath toDirectory:dirPath];
	}
	
	return NO;
}

- (BOOL)splitPlainText:(NSString *)filePath toDirectory:(NSString *)dirPath
{
	NSLog(@"Splitting plain text: %@ to: %@", filePath, dirPath);
}

- (BOOL)splitHTML:(NSString *)filePath toDirectory:(NSString *)dirPath
{
	NSLog(@"Splitting HTML: %@ to: %@", filePath, dirPath);
	NSRange headEnd = [lowercaseText rangeOfString:@"</head>" options:NSLiteralSearch];
	if (headEnd.location == NSNotFound)
		return NO;
	NSString *headText = [originalText substringWithRange:NSMakeRange(0, headEnd.location + 7)];
	int splitnum = 0;
	NSString *splitText;
	NSString *lineBreaker = [self getLineBreakCharacterForString:headText];
	switch (splitType)
	{
		case splitOnH1:
			splitText = @"<h1";
			break;
		case splitOnH2:
			splitText = @"<h2";
			break;
		case splitOnCenter:
			splitText = @"<center";
			break;
		case splitOnChapter:
			splitText = @"chapter";
			break;
		case splitOnOther:
			splitText = [splitString lowercaseString];
		case splitOnOtherAndText:
			splitText = [splitString lowercaseString];
			break;
		default:
			// Split on numeral here.
			splitText = @"?????";
			break;
	}
	if ((splitType != splitOnNumeral) && (splitType != splitOnNumeralAndText)) //TODO
	{
		int start = headEnd.location + 7;
		NSMutableString *currentStr = [[NSMutableString alloc] initWithString:headText];
		unsigned int len = [originalText length];
		unsigned int splitlen = [splitText length];
		int end;
		while ((start + splitlen) < len)
		{
			NSMutableString *currentStr = [[NSMutableString alloc] initWithString:headText];
			NSRange aRange = [lowercaseText rangeOfString:splitText options:NSLiteralSearch
													range:NSMakeRange(start + splitlen, (len - (start + splitlen)))];
			if (aRange.location == NSNotFound)
				end = len;
			else
				end = aRange.location;
			NSString *chunk = [originalText substringWithRange:NSMakeRange(start, (end - start))];
			if (splitnum !=0)
			{
				[currentStr appendFormat:@"<body>%@", lineBreaker];
			}
			[currentStr appendString:chunk];
			if (end != len)
			{
				[currentStr appendFormat:@"%@</body>%@</html>%@", lineBreaker, lineBreaker, lineBreaker];
			}
			
			//FIXME: make save name user-definable
			NSString *currentPath = [dirPath stringByAppendingPathComponent:
				[NSString stringWithFormat:@"%03d %@", splitnum++, [filePath lastPathComponent]]];
			BOOL worky = [currentStr writeToFile:currentPath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
			if (NO == worky)
				return NO;
			start = end;
			[currentStr release];
		}
	}
	return YES;
}

- (NSString *)getLineBreakCharacterForString:(NSString *)input
{
	NSRange aRange = [input rangeOfString:@"\r\n" options:NSLiteralSearch];
	if (aRange.location != NSNotFound)
		return [NSString stringWithString:@"\r\n"];  // Windoze
	aRange = [input rangeOfString:@"\n" options:NSLiteralSearch];
	if (aRange.location != NSNotFound)
		return [NSString stringWithString:@"\n"];  // UNIX
	aRange = [input rangeOfString:@"\r" options:NSLiteralSearch];
	if (aRange.location != NSNotFound)
		return [NSString stringWithString:@"\r"];  // Mac OS 1-9
	
	//When in doubt, assume UNIX for no good reason.
	return [NSString stringWithString:@"\n"];
}

- (void)dealloc
{
	if (nil != originalText)
	{
		[originalText release];
		[lowercaseText release];
	}
	[optionsDictionary release];
	[super dealloc];
}

@end
